package cn.iocoder.yudao.module.biz.controller.admin.pay.service.impl;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.biz.controller.admin.receivables.domain.SanBizContractArchiveReceiveRecord;
import cn.iocoder.yudao.module.biz.controller.admin.receivables.service.SanBizContractArchiveReceiveRecordService;
import cn.iocoder.yudao.module.biz.dal.dataobject.contract.ContractArchiveDO;
import cn.iocoder.yudao.module.biz.dal.mysql.contract.ContractArchiveMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.module.biz.controller.admin.pay.domain.SanBizPaymentManagement;
import cn.iocoder.yudao.module.biz.controller.admin.pay.service.SanBizPaymentManagementService;
import cn.iocoder.yudao.module.biz.controller.admin.pay.mapper.SanBizPaymentManagementMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
* @author 王兴鹏
* @description 针对表【san_biz_payment_management(收款管理表)】的数据库操作Service实现
* @createDate 2025-08-16 11:54:58
*/
@Service
public class SanBizPaymentManagementServiceImpl extends ServiceImpl<SanBizPaymentManagementMapper, SanBizPaymentManagement>
    implements SanBizPaymentManagementService{

    @Autowired
    private SanBizPaymentManagementMapper mapper;

    @Autowired
    private ContractArchiveMapper archiveMapper;

    @Resource
    private SanBizContractArchiveReceiveRecordService contractArchiveReceiveRecordService;

    @Override
    public IPage<SanBizPaymentManagement> getBizPaymentManagementPage(SanBizPaymentManagement pageReqVO) {
//        QueryWrapper queryWrapper = new QueryWrapper();
//        PageParam pageParam = new PageParam();
//        pageParam.setPageNo(pageReqVO.getPageNo());
//        pageParam.setPageSize(pageReqVO.getPageSize());
//        if(pageReqVO.getEffectDateStr() != null && pageReqVO.getEffectDateStr().size()> 1){
//            queryWrapper.ge("effect_date",pageReqVO.getEffectDateStr().get(0));
//            queryWrapper.le("effect_date",pageReqVO.getEffectDateStr().get(1));
//        }
//        if(StringUtils.isNotEmpty( pageReqVO.getContractCode())){
//            queryWrapper.eq("contract_code", pageReqVO.getContractCode());
//        }
//        IPage<SanBizPaymentManagement> mpPage = MyBatisUtils.buildPage(pageParam);
//       return mapper.selectPage(mpPage, queryWrapper);
        IPage<SanBizPaymentManagement> pageResult = new Page<>();
        pageResult.setRecords(mapper.getBizPaymentManagementPage(pageReqVO));
        pageResult.setTotal(mapper.getCount(pageReqVO));
        pageResult.setSize(pageReqVO.getPageSize());
        pageResult.setCurrent(pageReqVO.getPageNo());
        return pageResult;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class) // 添加事务，异常则回滚所有导入
    public String importList(List<SanBizPaymentManagement> list, Boolean updateSupport) {
//        saveBatch(list);
        if (list == null || list.size() == 0)
        {
            throw new ServiceException(4041,"导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
//        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SanBizPaymentManagement user : list)
        {
            try
            {
                // 验证是否存在
                QueryWrapper<ContractArchiveDO> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("contract_code",user.getContractCode());
                queryWrapper.eq("status","2");
                ContractArchiveDO u = archiveMapper.selectOne(queryWrapper);
                if(u == null) {
                    failureNum++;
                    String msg = "<br/>" + failureNum + "、合同 " + user.getContractCode() + " 不存在或者未生效 导入失败;";
                    failureMsg.append(msg);
                    log.error(msg);
                }
                else
                {
                    SanBizContractArchiveReceiveRecord con = mapper.getContractArchiveReceiveRecord(user);
                    if(con == null) {
                        failureNum++;
                        String msg = "<br/>" + failureNum + "、合同 " + user.getContractCode() + "期数"+ user.getPeriods() +" 未查询到此期数的合同数据 导入失败;";
                        failureMsg.append(msg);
                        log.error(msg);
                    } else {
                        user.setCreator(SecurityFrameworkUtils.getLoginUser().getId()+"");
                        user.setContractReceiveRecordId(con.getId());
                        /**
                         * formData.value.contractName = a.contractArchiveInfo.contractName
                         *       formData.value.contractCode = a.contractArchiveInfo.contractCode
                         *       formData.value.customerName = a.contractArchiveInfo.customerName
                         *       formData.value.customerId = a.contractArchiveInfo.customerId
                         *       formData.value.periods = a.instalmentCount
                         *       formData.value.serviceTeamName = a.contractArchiveInfo.serviceUnitName
                         *       formData.value.serviceTeamId = a.contractArchiveInfo.serviceUnitId
                         *       formData.value.type = a.contractArchiveInfo.contractType
                         *       formData.value.serviceTerm = a.serviceTerm
                         *       formData.value.totalMoney = a.receiveMoney
                         *       formData.value.effectDate = a.receiveDate
                         */
                        ContractArchiveDO contract = archiveMapper.getContractArchiveDetail(con.getContractArchiveId());
                        user.setContractName(contract.getContractName());
                        user.setCustomerId(contract.getCustomerId()+"");
                        user.setCustomerName(contract.getCustomerName());
                        user.setServiceTeamId(contract.getServiceUnitId()+"");
                        user.setServiceTeamName(contract.getServiceUnitName());
                        user.setType(contract.getContractType());

                        user.setServiceTerm(con.getServiceTerm());
                        user.setTotalMoney(con.getReceiveMoney());
                        LocalDateTime localDateTime = con.getReceiveDate();
                        String formatted = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date date = sdf.parse(formatted);
                        user.setEffectDate(date);
                        user.setContractId(con.getId()+"");
                        user.setCreateTime(LocalDateTime.now());
                        user.setUpdateTime(LocalDateTime.now());
                        user.setCreator(SecurityFrameworkUtils.getLoginUserId()+"");
                        this.save(user);

                        // 更新分期状态为已付款
                        UpdateWrapper wrapper = new UpdateWrapper();
                        wrapper.set("status","1");
                        wrapper.eq("id", con.getId());
                        contractArchiveReceiveRecordService.update(wrapper);

                        successNum++;
                        successMsg.append("<br/>" + successNum + "、合同 " + user.getContractCode() + " 导入成功");
                    }

                }
//                else if (updateSupport)
//                {
////                    BeanValidators.validateWithException(validator, user);
//                    user.setUpdater(SecurityFrameworkUtils.getLoginUser().getId()+"");
//                    user.setId(u.getId());
//                    this.updateById(user);
//                    successNum++;
//                    successMsg.append("<br/>" + successNum + "、合同 " + user.getContractCode() + " 更新成功");
//                }
//                else
//                {
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、合同 " + user.getContractCode() + " 已存在");
//                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、合同 " + user.getContractCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
//            throw new ServiceException(4041,failureMsg.toString());
            return failureMsg.toString();
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            return successMsg.toString();
        }
    }
}




